﻿using Gym.Application.Common.Interfaces;
using Gym.Application.Profiles.Common;
using Gym.Domain.Profiles;
using Gym.Domain.TrainerAggregate;
using Microsoft.EntityFrameworkCore;

namespace Gym.Infrastructure.Persistence.Repositories
{
    public class TrainersRepository : ITrainersRepository
    {
        private readonly GymDbContext _dbContext;
        public TrainersRepository(GymDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public async Task AddTrainerAsync(Trainer trainer)
        {
            await _dbContext.Trainers.AddAsync(trainer);
            await _dbContext.SaveChangesAsync();
        }

        public async Task<Trainer?> GetByIdAsync(Guid trainerId)
        {
            return await _dbContext.Trainers.FirstOrDefaultAsync(trainer => trainer.Id == trainerId);
        }

        public async Task<Profile?> GetProfileByUserIdAsync(Guid userId)
        {
            var trainer = await _dbContext.Trainers
            .AsNoTracking()
            .FirstOrDefaultAsync(trainer => trainer.UserId == userId);

            return trainer is null ? null : new Profile(trainer.Id, ProfileType.Trainer);
        }

        public async Task UpdateAsync(Trainer trainer)
        {
            _dbContext.Trainers.Update(trainer);
            await _dbContext.SaveChangesAsync();
        }
    }
}
